﻿Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.ComponentModel

<Assembly: WebResource("YCFramework.iconeYCUpload.png", "image/png")> 

'TODO: Mudar para que esse controle seja usado apenas para upload de imagens
Namespace Controle
    <ToolboxData("<{0}:YCFileUpload runat=""server""></{0}:YCFileUpload>")> _
    Public Class YCFileUpload
        Inherits FileUpload

#Region "Variaveis"
        Private pLocalSalvar As String = Nothing

        Private pIsImage As Boolean

        Private pImgWidth As Integer
        Private pImgHeight As Integer

        Private pThumbnailWidth As Integer
        Private pThumbnailHeight As Integer

        Public Event ImagemSalva()
        Private pLinkImagem As String

        Private pTipoImagem As EnumTipoImagem = EnumTipoImagem.JPG
#End Region

#Region "Property"

        Public Enum EnumTipoImagem
            JPG
            PNG
            BMP
        End Enum

        Public Property TipoImagem() As EnumTipoImagem
            Get
                Return pTipoImagem
            End Get
            Set(ByVal value As EnumTipoImagem)
                pTipoImagem = value
            End Set
        End Property

        Public ReadOnly Property LinkImagem()
            Get
                Return pLinkImagem
            End Get
        End Property

        Public Property ImgWidth() As Integer
            Get
                Return pImgWidth
            End Get
            Set(ByVal value As Integer)
                pImgWidth = value
            End Set
        End Property

        Public Property ImgHeight() As Integer
            Get
                Return pImgHeight
            End Get
            Set(ByVal value As Integer)
                pImgHeight = value
            End Set
        End Property

        Public Property ThumbnailWidth() As Integer
            Get
                Return pThumbnailWidth
            End Get
            Set(ByVal value As Integer)
                pThumbnailWidth = value
            End Set
        End Property

        Public Property ThumbnailHeight() As Integer
            Get
                Return pThumbnailHeight
            End Get
            Set(ByVal value As Integer)
                pThumbnailHeight = value
            End Set
        End Property

        Public Property LocalSalvar() As String
            Get
                Return pLocalSalvar
            End Get
            Set(ByVal value As String)
                pLocalSalvar = value.Replace("/", "\")
            End Set
        End Property

        Public Property IsImage() As Boolean
            Get
                Return pIsImage
            End Get
            Set(ByVal value As Boolean)
                pIsImage = value
            End Set
        End Property

#End Region

        Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
            MyBase.OnPreRender(e)
            'TODO: Verificar se ocorre erro quando tem 2 ou + controles na mesma tela, por causa do __doPostBack
            Me.Attributes.Add("onchange", "if(confirm(""Deseja enviar esse arquivo?""))__doPostBack('','upload'); else this.value = """";")
        End Sub

        'TODO: Procurar outra forma de fazer isso. Tirar do _Load
        Private Sub YCFileUpload_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If pLocalSalvar Is Nothing Then _
                    Throw New ArgumentException("Selecione o local para salvar a imagem.")

                If Me.FileBytes.Length > 0 Then
                    If IsImage Then

                        Dim upBmp As Bitmap = Bitmap.FromStream(Me.PostedFile.InputStream)

                        pLinkImagem = String.Format("{0:ddMMyyyyHHmmss}.{1}", Now, pTipoImagem.ToString)

                        RedimensionaImagem(upBmp, pLinkImagem, pImgWidth, pImgHeight)

                        If pThumbnailWidth <> Nothing And pThumbnailHeight <> Nothing Then
                            RedimensionaImagem(upBmp, "thumb_" & pLinkImagem, pThumbnailWidth, pThumbnailHeight)
                        End If

                        RaiseEvent ImagemSalva()
                    End If
                End If
            Catch ex As Exception
            End Try
        End Sub

        ''' <summary>
        ''' Método que redimensiona a imagem mantendo a proporção
        ''' </summary>
        ''' <param name="img"></param>
        ''' <param name="NomeImagem"></param>
        ''' <param name="NewWidth">Largura máxima que a imagem vai ter</param>
        ''' <param name="NewHeight">Altura máxima que a imagem vai ter</param>
        ''' <remarks></remarks>
        Private Sub RedimensionaImagem(ByVal img As Bitmap, ByVal NomeImagem As String, ByVal NewWidth As Integer, ByVal NewHeight As Integer)
            Dim Largura, Altura As Decimal
            Dim Fator As Decimal = 0
            If img.Width / NewWidth > img.Height / NewHeight Then
                Fator = img.Width / NewWidth
            Else
                Fator = img.Height / NewHeight
            End If
            Largura = img.Width / Fator
            Altura = img.Height / Fator

            'TODO: Procurar outra forma de fazer isso
            img.GetThumbnailImage(Largura, Altura, New System.Drawing.Image.GetThumbnailImageAbort(AddressOf thumbnailcallback), IntPtr.Zero).Save(pLocalSalvar & "\" & NomeImagem, ImageFormat.Jpeg)
        End Sub

        Function thumbnailcallback() As Boolean
            Return False
        End Function


        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            With writer
                .Write("<span style=""display:block;overflow:hidden;position:relative;width:140px;border-left:2px groove #D4D0C8;"">")
                ' .Write(String.Format("<img src=""{0}"" style=""width: 45px; position:absolute;"" />", Page.ClientScript.GetWebResourceUrl(GetType(YCTextBox), "YCFramework.iconeYCUpload.png")))

                MyBase.Style.Add("position", "relative")
                MyBase.Style.Add("right", "80px")
                MyBase.Render(writer)

                .Write("</span>")
            End With

        End Sub

    End Class

End Namespace